//
//  AppDelegate.m
//  Custom_Weibo
//
//  Created by LEO on 12/7/15.
//  Copyright © 2015 Leo_Lei. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabBarController.h"
#import "LeftTableViewController.h"
#import "RightViewController.h"

@interface AppDelegate ()<CLLocationManagerDelegate> {
    CLLocationManager *_locationManager;
}

@end

@implementation AppDelegate

#pragma mark - SYSTEM_METHOD
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //Create a weibo object.
    self.sinaWeibo = [[SinaWeibo alloc] initWithAppKey:kAppKey
                                             appSecret:kAppSecret
                                        appRedirectURI:kAppRedirectURL
                                           andDelegate:self];
    
    //  Use SDK to create a manager controller.
    BaseTabBarController *baseTab = [[BaseTabBarController alloc] init];
    LeftTableViewController *leftController = [[LeftTableViewController alloc]
                                               initWithStyle:UITableViewStyleGrouped];
    RightViewController *rightController = [[RightViewController alloc] init];
    
    MMDrawerController *draweController = [[MMDrawerController alloc]
                                           initWithCenterViewController:baseTab
                                           leftDrawerViewController:leftController
                                           rightDrawerViewController:rightController];
    
    //  Set the side controllers' width.
    [draweController setMaximumLeftDrawerWidth:kLeftDrawerWidth];
    [draweController setMaximumRightDrawerWidth:kRightDrawerWidth];
    
    //  Set gesture available mode.
    [draweController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [draweController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    
    //  Set animation while dragging.
    MMDrawerControllerDrawerVisualStateBlock block = [MMDrawerVisualState swingingDoorVisualStateBlock];
    [draweController setDrawerVisualStateBlock:block];
    
    //  Using a custom window.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    self.window.rootViewController = draweController;
    
    //  Read stored information.
    [self readAuthData];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - LOG_IN
- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo {
    NSLog(@"You account is already log in");
    [self storeAuthData];
}

#pragma mark LOG_OUT
- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo {
    NSLog(@"You account is already log out");
}

#pragma mark STORE_DATA
- (void)storeAuthData {
    //Save the file into sandbox.
    SinaWeibo *sinaWeibo = [self sinaWeibo];
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaWeibo.accessToken, kAccessToken,
                              sinaWeibo.expirationDate, kExpirationDate,
                              sinaWeibo.userID, kUserID,
                              nil];
    
    //Data saved.
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:kAuthDataName];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark READ_DATA
- (void)readAuthData {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *weiboInfo = [defaults objectForKey:kAuthDataName];
    
    NSString *accessToken = [weiboInfo objectForKey:kAccessToken];
    NSDate *expirationDate = [weiboInfo objectForKey:kExpirationDate];
    NSString *userID = [weiboInfo objectForKey:kUserID];
    
    if (accessToken && expirationDate && userID ) {
        self.sinaWeibo.accessToken = accessToken;
        self.sinaWeibo.expirationDate = expirationDate;
        self.sinaWeibo.userID = userID;
        //  When access in, get the right of locating.
        [self getLocation];
    }
}

#pragma mark - LOCATION_GET
- (void)getLocation {
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        if (DEVICE_AVALIABLE_IOS8) {
            /*  Ask the device for permission,when using the application, it
             will request for location visit.
             You can also set it as 'requestAlwaysAuthorization', then
             application will continuously updating location,even if you aren't
             using the application.
             */
            [_locationManager requestWhenInUseAuthorization];
        }
    }
    //  Set the accuracy of locating for current location.
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    
    _locationManager.delegate = self;
    
    //  Begin updating location.
    [_locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    [_locationManager stopUpdatingLocation];
}
@end
